<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title><?php echo $this->titre; ?></title>
	<style>
	
	@import url(../css/chord.css);
	@import url(../css/legende.css);
	
	#circle circle {
	  fill: none;
	  pointer-events: all;
	}
	
	.group path {
	  fill-opacity: .5;
	}
	
	path.chord {
	  stroke: #000;
	  stroke-width: .25px;
	}
	
	#circle:hover path.fade {
	  display: none;
	}
	
	</style>
    <script type='text/javascript' src='../js/d3.V2.js' ></script>
    <script type='text/javascript' src='../js/legende.js' ></script>
  </head>

  <body style="margin:30px; ">
    <div class="body">
      <div class="content">
		<h1 id='chord_chart'><?php echo $this->titre; ?></h1>
		<h3><?php 
			if($this->tags){
				echo "<a href='".$this->urlStats."'>DATA</a>";
				if($this->tags==1)
					echo " pour le tag :";
				else
					echo " pour le(s) tag(s) :";
				$urlTags = "";
				foreach ($this->tags as $t){
					echo " ".$t." -"; 
					$urlTags .= "&tags[]=".$t;
				}
			}
			?>
		</h3>
		<h3>Base de données : 
			<select id="sBase" onselect="changeBase()" >
			<?php 
				foreach ($this->bases as $id=>$titre){
					$s="";
					if($id==$this->idBase)$s='selected="selected"'; 
					echo "<option $s value='".$id."'>".$titre."</option>"; 
				}
			?>
			</select> 
		</h3>
		<div id='legende'> </div>
		<table >
			<tr>
				<td style="width:720px;vertical-align:top;" ><div id='chart'> </div></td>
				<td style="width:100%;vertical-align:top;" ><div id='docs' style="height:720px;overflow:auto;" > </div></td>
			</tr>
		</table>
      </div>
	<p>Merci beaucoup à <a href='http://bost.ocks.org/mike/uberdata/'>Mike Bostock</a>.</p>

	</div>

	<script>
	
    var idBase = '<?php echo $this->idBase; ?>';
    var urlTags = '<?php echo $urlTags; ?>';
    var fill = d3.scale.category20b();
    var colors = [];
    colors['nbDoc'] = ["#ccdef0", "#1e4164"];
    colors['value'] = ["#f1c4c5", "#621819"];
	
	var width = 720,
	    height = 720,
	    outerRadius = Math.min(width, height) / 2 - 10,
	    innerRadius = outerRadius - 24;
	
	//var formatPercent = d3.format(".1%");
	
	var arc = d3.svg.arc()
	    .innerRadius(innerRadius)
	    .outerRadius(outerRadius);
	
	var layout = d3.layout.chord()
	    .padding(.04)
	    .sortSubgroups(d3.descending)
	    .sortChords(d3.ascending);
	
	var path = d3.svg.chord()
	    .radius(innerRadius);
	
    var allData, fillNbDoc, fillValue;
	var tags, matrice;
	
	d3.json("<?php echo $this->urlStats; ?>", function(donnees) {
		allData = donnees;
		tags = donnees.tags;
		matrice = donnees.matrice;     

		//calcule les dimensions
		var arrNbDoc = tags.map(function(x) { return parseInt(x.nbDoc); });
		var arrValue = tags.map(function(x) { return parseInt(x.value); });
		var arrNbRela = tags.map(function(x) { return parseInt(x.nbRela); });
		var arrNbCoo = tags.map(function(x) { return parseInt(x.nbCoo); });
		//calcule les extrémité
		var exNbDoc = d3.extent(arrNbDoc);
		var exValue = d3.extent(arrValue);
		var exNbRela = d3.extent(arrNbRela);
		var exNbCoo = d3.extent(arrNbCoo);
		//calcule les intervals de couleurs
	    fillNbDoc = d3.scale.log().domain(exNbDoc).range(colors['nbDoc']);
	    fillValue = d3.scale.log().domain(exValue).range(colors['value']);

		//ajoute la légende
		var leg = new legende({id:"legende"
			, fctFiltre:filtreDonnees
			, data:{valeurs:tags,dimensions:["nbDoc","nbRela","value","nbCoo"],y:[exNbDoc,exNbRela,exValue,exNbCoo]}});

		drawChord();
		

	});

	function drawChord() {
		
		if(d3.select("#svgChord"))d3.select("#svgChord").remove();
		svg = d3.select("#chart").append("svg")
		    .attr("id", "svgChord")
		    .attr("width", width)
		    .attr("height", height)
		  .append("g")
		    .attr("id", "circle")
		    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
		
		svg.append("circle")
		    .attr("r", outerRadius);
		
	    // Compute the chord layout.
	    layout.matrix(matrice);
	
	    // Add a group per tag
	    group = svg.selectAll(".group")
	        .data(layout.groups)
	      .enter().append("g")
	        .attr("class", "group")
	        .on("click", clickGroup)
	        .on("mouseover", mouseover);
	
	    // Add a mouseover title.
	    group.append("title").text(function(d, i) {
		  var nbDoc = tags[i].nbTronc && tags[i].nbTronc > 0 ? tags[i].nbTronc : tags[i].nbDoc; 
	      return i + "_"+tags[i].tag_id + " "+tags[i].code + ": utilisé pour "+nbDoc+" document(s)";
	    });
	
	    // Add the group arc.
	    groupPath = group.append("path")
	        .attr("id", function(d, i) { return "group" + i; })
	        .attr("d", arc)
	        .style("fill", function(d, i) { return fillNbDoc(tags[i].value);});
	
	    // Add a text label.
	    groupText = group.append("text")
	        .attr("x", 6)
	        .attr("dy", 15);
	
	    groupText.append("textPath")
	        .attr("xlink:href", function(d, i) { return "#group" + i; })
	        .text(function(d, i) { return tags[i].code; });
	
	    // Remove the labels that don't fit. :(
	    groupText.filter(function(d, i) { return groupPath[0][i].getTotalLength() / 2 - 16 < this.getComputedTextLength(); })
	        .remove();
		
	    // Add the chords.
	    chord = svg.selectAll(".chord")
	        .data(layout.chords)
	      .enter().append("path")
	        .attr("class", "chord")
	        .style("fill", function(d) { return fillValue(d.source.value); })
	        .attr("d", path)
	        .on("click", clickChord);
	
	    // Add an elaborate mouseover title for each chod.
	    chord.append("title").text(function(d) {
	      return tags[d.source.index].code
	          + " → " + tags[d.target.index].code
	          + ": " + d.source.value
	          + "\n" + tags[d.target.index].code
	          + " → " + tags[d.source.index].code
	          + ": " + d.target.value;
	    });
		console.log("drawChord : fin");
	
	}	

    function mouseover(d, i) {
	      chord.classed("fade", function(p) {
	        return p.source.index != i
	            && p.target.index != i;
	      });
	    }
	
	function clickGroup(d, i) {
		var racine = "&racine=oui";
		if(tags[i]['nbTronc'] && tags[i]['nbTronc']<=0)racine = "";
		var url = "../flux/docs?idBase="+idBase+"&tag="+tags[i]['tag_id']+"&liste=oui"+racine+urlTags;
		drawDocListe(url);
	}	

	function clickChord(d, i) {
		var racine = "&racine=oui";
		var iSrc = d.source.index;
		var iDst = d.target.index;
		if(tags[iSrc]['nbTronc'] && tags[iSrc]['nbTronc']<=0)racine = "";
		var url = "../flux/docs?idBase="+idBase+"&tag="+tags[iSrc]['tag_id']+","+tags[iDst]['tag_id']+"&liste=oui"+racine+urlTags;
		drawDocListe(url);
	}

	function drawDocListe(url){
		d3.json(url, function(docs) {
			console.log("d : "+docs.length);
			if(d3.select("#tabDoc"))d3.select("#tabDoc").remove();
			var divDoc = d3.select("#docs").append("div")
			    .attr("id", "tabDoc");

			// Add a group per tag
			divDoc.selectAll(".iDoc")
		        .data(docs)
		      .enter().append("div")
		        .attr("class", "iDoc")
		        .html(function(d) { 
					var html = "- "+d.titre+" (<a href='"+d.url+"'>détail</a>)<p>"+d.note+"</p>"; 
			        return html; 
			        });
			
		});	
	}	
	
	function filtreDonnees(actives, extents) {
		var filtre = [], num=0;
		//filtrage des données
		//conserve les tags qui sont dans la matrice
		/*
		allData.tags.forEach(function(d) {
		    actives.forEach(function(p, i) {
		      b = extents[i][0] <= d[p] && d[p] <= extents[i][1];
			  if(b){
				//conserve le tag
				filtre[num]=d;	
				allData.matrice[num].forEach(function(q, j) {
					if(q>0)filtre[j]=allData.tags[j];	
				});
			  }
		    });
		    num++;
		});
		*/

		//garde uniquement les tags qui respecte toute les conditions
		allData.tags.forEach(function(d) {
		    if(actives.every(function(p, i) {
			      return extents[i][0] <= d[p] && d[p] <= extents[i][1];
			    })){
			     filtre[num]=d;
		    }
		    num++;
		});
		
		//constitution des tableaux
		tags = [];
		matrice = [];
		for (key in filtre) {
			tags.push(filtre[key]);
			var mtc = [];
		    //suprime les dimensions inutile de la matrice
			allData.matrice[key].forEach(function(p, i) {
				if(filtre[i])mtc.push(p);
			});
			matrice.push(mtc);
		}
		  console.log("filtreDonnees : fin : tags.length = "+tags.length);
		  if(tags.length==1){
			  //il faut au minimum deux tags pour que la visualisation soit valide
			  tags = [];
			  matrice = [];
		  }
		  drawChord();
	}
	
	</script>

  </body>
</html>
